package com.evolutioninc.fortunecookie;

import java.util.Random;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RemoteViews;
import android.widget.Toast;

public class FortuneCookieWidget extends AppWidgetProvider {
	private static String action_widget_update;
	private static String[] fortunesArray;
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		
		RemoteViews widgetView = new RemoteViews(context.getPackageName(), R.layout.widget);
		action_widget_update = context.getResources().getString(R.string.ACTION_WIDGET_UPDATE);
		
		// Define pending intent to send broadcast when widget button is clicked
		
		Intent widgetUpdateIntent = new Intent(context, FortuneCookieWidget.class);
		widgetUpdateIntent.setAction(action_widget_update);
		PendingIntent widgetUpdatePIntent = PendingIntent.getBroadcast(context, 0, widgetUpdateIntent, 0);
		widgetView.setOnClickPendingIntent(R.id.widget_button, widgetUpdatePIntent);
		
		// Update all widget instances
		for(int i = 0; i < appWidgetIds.length; i++) {
			appWidgetManager.updateAppWidget(appWidgetIds[i], widgetView);
		}
		
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		RemoteViews widgetView = new RemoteViews(context.getPackageName(), R.layout.widget);
		
		if(intent.getAction().equals(action_widget_update)) {
			// Locate fortunes from XML file
			if(fortunesArray == null)
				fortunesArray = context.getResources().getStringArray(R.array.fortune_array);
			
			// Select and set a random fortune
			Random randGen = new Random();
			String newFortune = fortunesArray[randGen.nextInt(fortunesArray.length)];
			widgetView.setTextViewText(R.id.widget_text, newFortune);
			
			// Update widget
			ComponentName widgetCN = new ComponentName(context, FortuneCookieWidget.class);
			AppWidgetManager.getInstance(context).updateAppWidget(widgetCN, widgetView);
		}
		
		super.onReceive(context, intent);
	}
}
